import { getScrumDetail } from '../services/scrum';


const getScrumMap = (scrumData) => {
  let scrumMap = {}
  let laneListLength = scrumData.laneList.length;
  for (let i = 0; i < laneListLength; i++) {
    let blockListLength = scrumData.laneList[i].blockList.length;
    for (let k = 0; k < blockListLength; k++) {
      scrumMap[scrumData.laneList[i].id + "-" + scrumData.laneList[i].blockList[k].id] = scrumData.laneList[i].blockList[k]
    }
  }
  return scrumMap;
}

export default {
  namespace: 'scrum',
  state: {
    scrumData: [],
  },
  effects: {
    *queryScurm({ payload }, { call, put }) {
      console.log(payload)
      const response = yield call(getScrumDetail, payload);
      yield put({
        type: 'setScrumDetail',
        payload: response,
      });
    },

    *blockReorder({ payload }, { call, put }){
      console.log(payload)
      yield put({
        type: 'setBlockReorderResult',
        payload: payload,
      });
    },

    *reorder({ payload }, { call, put }) {
      console.log(payload);
      yield put({
        type: 'setReorderResult',
        payload: payload,
      });
    },

    *move({ payload }, { call, put }) {
      console.log(payload);
      yield put({
        type: 'setMoveResult',
        payload: payload,
      });
    }
  },
  reducers: {
    setScrumDetail(state, action) {
      return { ...state, scrumData: action.payload };
    },
    setReorderResult(state, action) {
      let scrumMap = getScrumMap(state.scrumData);
      console.log(scrumMap)
      let blockData = scrumMap[action.payload.laneId + "-" + action.payload.blockId];
      blockData.taskList = action.payload.reorderTaskList;
      console.log(state.scrumData)
      return { ...state, scrumData: state.scrumData };
    },
    setMoveResult(state, action) {
      let scrumMap = getScrumMap(state.scrumData);
      let blockData = scrumMap[action.payload.laneId + "-" + action.payload.blockId];
      let targetblockData = scrumMap[action.payload.targetBlaneId + "-" + action.payload.targetBlockId];
      blockData.taskList = action.payload.sourceTaskList;
      targetblockData.taskList = action.payload.targetTaskList;
      return { ...state, scrumData: state.scrumData };
    },
    setBlockReorderResult(state, action) {
      let  sourceBlockIndex = action.payload.sourceBlockIndex;
      let  targetBlockIndex = action.payload.targetBlockIndex;
      state.scrumData.laneList.forEach(lane => {
        let blockList = [... lane.blockList];
        let [removed] = blockList.splice(sourceBlockIndex, 1);
        blockList.splice(targetBlockIndex, 0, removed);
        lane.blockList = blockList;
      });
      return {...state, scrumData: state.scrumData }
    }
  },
};